package com.company.cloud.page.modules.mgr.controller;

import com.company.cloud.common.bean.BaseClientResult;

import com.company.cloud.page.modules.api.models.PageComponentModel;
import com.company.cloud.page.modules.base.entity.PageComponentInfo;
import com.company.cloud.user.modules.api.response.UserSimple;
import com.company.cloud.user.modules.api.service.UserRemoteService;
import com.company.common.server.config.cloud.ProjectConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.bean.LoginUserInfo;
import com.company.cloud.common.constant.BaseConstant.EnabledEnum;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.page.constant.PageCardTypeEnum;
import com.company.cloud.page.modules.base.entity.PageCardConfigInfo;
import com.company.cloud.page.modules.base.service.PageCardConfigInfoService;
import com.company.cloud.page.modules.cache.models.PageCardModel;
import com.company.cloud.page.modules.cache.service.PageCardCacheService;
import com.company.cloud.page.modules.cache.utils.PageCachekeys;
import com.company.cloud.page.modules.cache.utils.PageConvertUtils;
import com.company.cloud.page.modules.mgr.controller.req.PageCardQuery4PageParam;
import com.company.cloud.page.modules.mgr.controller.req.PageCardSaveParam;
import com.company.cloud.page.modules.mgr.controller.req.PageCardUpdateParam;
import com.company.cloud.page.modules.mgr.service.PageCardConfigMgrService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;

/**
 * 名片配置信息管理
 */
@Authc
@RestController
@RequestMapping("/mgr/cms/pageCardConfig")
@Api(tags = "Page_MGR_名片配置信息管理")
public class PageCardConfigController {


	@Autowired
	private PageCardConfigInfoService pageCardConfigInfoService;
	@Autowired
	private PageCardCacheService pageCardCacheService;
	@Autowired
	private PageCardConfigMgrService pageCardConfigMgrService;
	@Autowired
	private UserRemoteService userRemoteService;
	@Autowired
	private ProjectConfig projectConfig;

	@PostMapping("/query")
	@ApiOperation(value = "列表查询", response = PageCardModel.class)
	public BaseResult query(@RequestBody PageCardQuery4PageParam params) {
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		IPage<PageCardConfigInfo> page = pageCardConfigInfoService.page(
				new Page<PageCardConfigInfo>(params.getPage(), params.getRows()),
				new QueryWrapper<PageCardConfigInfo>()
						.eq("company_no", userInfo.getCompanyNo())
						.like(StringUtils.hasText(params.getPageName()), "page_name", params.getPageName())
						.eq(StringUtils.hasText(params.getPageType()), "page_type", params.getPageType())
						.eq(StringUtils.hasText(params.getIsDraft()), "is_draft", params.getIsDraft())
						.eq("rows_state", EnabledEnum.ENABLED.getCode())
						.orderByDesc("cdt"));

		Set<Integer> ids = new HashSet<>();
		ids.add(0);
		page.getRecords().forEach(info->{
			ids.add(info.getUserId());
		});
		BaseClientResult<Map<Integer, UserSimple>> userMapResp = userRemoteService.getUserMapByIds(ids);

		if (!CheckUtils.hasClientResult(userMapResp)) {
			throw new BusinessException(userMapResp.getCode(), userMapResp.getMsg());
		}
		IPage<PageCardModel> data = page.convert(new Function<PageCardConfigInfo, PageCardModel>() {
			@Override
			public PageCardModel apply(PageCardConfigInfo entity) {
				return PageConvertUtils.getPageCardModel(entity, userMapResp.getData());
			}
		});
		return BaseResult.ok(data);
	}

	@GetMapping("/get")
	@ApiOperation(value = "详情", response = PageCardModel.class)
	public BaseResult get(@RequestParam("pageNo") String pageNo) {
		PageCardModel data= pageCardCacheService.getPageCardConfigDB(pageNo);
		return BaseResult.ok(data);
	}

	@GetMapping("/getByUser")
	@ApiOperation(value = "根据当前用户获取名片详情", response = PageCardModel.class)
	public BaseResult getByUser() {
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		PageCardConfigInfo entity = pageCardConfigMgrService.getConfigByUser(userInfo);
		if (entity != null) {
			PageCardModel data= pageCardCacheService.getPageCardConfigDB(entity.getPageNo());
			return BaseResult.ok(data);
		}
		return BaseResult.ok();
	}

	@GetMapping("/getByUserId")
	@ApiOperation(value = "根据用户Id获取名片详情", response = PageCardModel.class)
	public BaseResult getByUserId(@RequestParam("userId") Integer userId) {
		if(userId==null || userId<=0){
			throw new BusinessException(BaseReturnEnum.PARAM_NULL);
		}
		BaseClientResult<UserSimple> userResult= userRemoteService.getUserById(userId);
		UserSimple userSimple=BaseClientResult.getResultData(userResult);
		LoginSimpleUserInfo userInfo =new LoginSimpleUserInfo();
		userInfo.setId(userSimple.getId());
		userInfo.setCompanyNo(userSimple.getCompanyNo());
		PageCardConfigInfo entity = pageCardConfigMgrService.getConfigByUser(userInfo);
		if (entity != null) {
			PageCardModel data= pageCardCacheService.getPageCardConfigDB(entity.getPageNo());
			return BaseResult.ok(data);
		}
		return BaseResult.ok();
	}



	@GetMapping("/getConfig2DataByUser")
	@ApiOperation(value = "根据当前用户获取名片详情和数据", response = PageCardModel.class)
	public BaseResult getConfig2DataByUser() {
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		PageCardConfigInfo entity = pageCardConfigMgrService.getConfigByUser(userInfo);
		if (entity == null) {
			return BaseResult.ok();
		}
		PageCardModel data= pageCardCacheService.getPageCardConfig2DataByDB(entity.getPageNo(),userInfo);
		return BaseResult.ok(data);
	}

	@PostMapping("/save2update")
	@ApiOperation(value = "新增或修改", response = BaseResult.class)
	public BaseResult save2update(@RequestBody PageCardSaveParam params) {
		ValidatorUtils.validate(params);
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		PageCardConfigInfo entity =pageCardConfigMgrService.addOrUpdate(params,userInfo);
		pageCardCacheService.removePageCardConfigCache(entity.getPageNo());
		return BaseResult.ok();
	}


	@GetMapping("/delete")
	@ApiOperation(value = "删除", response = BaseResult.class)
	public BaseResult delete(@RequestParam("pageNo") String pageNo) {
		if (CheckUtils.isEmpty(pageNo)) {
			throw new BusinessException(BaseReturnEnum.PARAM_NULL);
		}
		PageCardConfigInfo entity = pageCardConfigInfoService.getById(pageNo);
		if (entity == null || EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
			throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
		}
		LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
		entity.setRowsState(EnabledEnum.DISABLED.getCode());
		entity.addEditParam(userInfo);
		pageCardConfigInfoService.updateById(entity);
		pageCardCacheService.removePageCardConfigCache(entity.getPageNo());
		return BaseResult.ok();
	}

}
